package com.example.qu_tao.View;

import android.Manifest;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import com.example.qu_tao.R;

public class GeRenZhongXinActivity extends AppCompatActivity {

    private static final int PICK_IMAGE_REQUEST = 1;
    private static final int PERMISSION_REQUEST_READ_EXTERNAL_STORAGE = 2;
    private EditText etNickname, etPhone, etAge, etRegion;
    private Button btnSave;
    private ImageView profileImage;
    private TextView editProfileImage;
    private String selectedImagePath;
    private ImageView back;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_gerenzhongxin);

        etNickname = findViewById(R.id.et_nickname);
        etPhone = findViewById(R.id.et_phone);
        etAge = findViewById(R.id.et_age);
        etRegion = findViewById(R.id.et_region);
        btnSave = findViewById(R.id.btn_save);
        profileImage = findViewById(R.id.profile_image);
        editProfileImage = findViewById(R.id.edit_profile_image);
        back = findViewById(R.id.back_button);

        loadUserInfo();

        editProfileImage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (ContextCompat.checkSelfPermission(GeRenZhongXinActivity.this, Manifest.permission.READ_EXTERNAL_STORAGE)
                        != PackageManager.PERMISSION_GRANTED) {
                    ActivityCompat.requestPermissions(GeRenZhongXinActivity.this,
                            new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
                            PERMISSION_REQUEST_READ_EXTERNAL_STORAGE);
                } else {
                    openGallery();
                }
            }
        });

        btnSave.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                saveProfile();
            }
        });
        back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        loadProfileImage();
    }

    private void loadUserInfo() {
        SharedPreferences sharedPreferences = getSharedPreferences("user_info", MODE_PRIVATE);
        long userId = sharedPreferences.getLong("user_id", -1);

        if (userId != -1) {
            Uri uri = Uri.parse("content://com.example.qu_tao.provider/user/" + userId);
            String[] projection = {"user_name", "user_phone"};
            ContentResolver contentResolver = getContentResolver();
            Cursor cursor = contentResolver.query(uri, projection, null, null, null);
            if (cursor != null && cursor.moveToFirst()) {
                int userNameIndex = cursor.getColumnIndex("user_name");
                int userPhoneIndex = cursor.getColumnIndex("user_phone");

                if (userNameIndex >= 0 && userPhoneIndex >= 0) {
                    String userName = cursor.getString(userNameIndex);
                    String userPhone = cursor.getString(userPhoneIndex);
                    etNickname.setText(userName);
                    etPhone.setText(userPhone);
                }
                cursor.close();
            }
        }

        // 加载年龄和地区信息
        String age = sharedPreferences.getString("age", "");
        String region = sharedPreferences.getString("region", "");
        etAge.setText(age);
        etRegion.setText(region);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == PERMISSION_REQUEST_READ_EXTERNAL_STORAGE) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                openGallery();
            }
        }
    }

    private void openGallery() {
        Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        startActivityForResult(intent, PICK_IMAGE_REQUEST);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null) {
            Uri selectedImage = data.getData();
            String[] filePathColumn = {MediaStore.Images.Media.DATA};
            Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null);
            if (cursor != null) {
                cursor.moveToFirst();
                int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
                selectedImagePath = cursor.getString(columnIndex);
                cursor.close();
                // 压缩图片
                Bitmap bitmap = decodeSampledBitmapFromResource(selectedImagePath, profileImage.getWidth(), profileImage.getHeight());
                if (bitmap != null) {
                    profileImage.setImageBitmap(bitmap);
                }
            }
        }
    }

    private void saveProfile() {
        String nickname = etNickname.getText().toString();
        String phone = etPhone.getText().toString();
        String age = etAge.getText().toString();
        String region = etRegion.getText().toString();

        // 保存图片路径到 SharedPreferences
        SharedPreferences sharedPreferences = getSharedPreferences("user_info", MODE_PRIVATE);
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.putString("profile_image_path", selectedImagePath);
        editor.putString("age", age);
        editor.putString("region", region);
        editor.apply();

        long userId = sharedPreferences.getLong("user_id", -1);
        if (userId != -1) {
            Uri uri = Uri.parse("content://com.example.qu_tao.provider/user/" + userId);
            ContentValues values = new ContentValues();
            values.put("user_name", nickname);
            values.put("user_phone", phone);
            getContentResolver().update(uri, values, null, null);
        }

        Intent intent = new Intent();
        intent.putExtra("nickname", nickname);
        intent.putExtra("phone", phone);
        intent.putExtra("age", age);
        intent.putExtra("region", region);
        intent.putExtra("profile_image_path", selectedImagePath);
        setResult(RESULT_OK, intent);
        finish();
    }

    private void loadProfileImage() {
        SharedPreferences sharedPreferences = getSharedPreferences("user_info", MODE_PRIVATE);
        String profileImagePath = sharedPreferences.getString("profile_image_path", null);
        if (profileImagePath != null) {
            // 压缩图片
            Bitmap bitmap = decodeSampledBitmapFromResource(profileImagePath, profileImage.getWidth(), profileImage.getHeight());
            if (bitmap != null) {
                profileImage.setImageBitmap(bitmap);
            }
        } else {
            // 显示默认头像
            profileImage.setImageResource(R.mipmap.haimianbaobao);
        }
    }

    private Bitmap decodeSampledBitmapFromResource(String path, int reqWidth, int reqHeight) {
        // 设置默认值避免除以零
        if (reqWidth <= 0) reqWidth = 300;
        if (reqHeight <= 0) reqHeight = 300;
        final BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(path, options);
        options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
        options.inJustDecodeBounds = false;
        return BitmapFactory.decodeFile(path, options);
    }

    private int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) {
        final int height = options.outHeight;
        final int width = options.outWidth;
        int inSampleSize = 1;
        if (height > reqHeight || width > reqWidth) {
            final int halfHeight = height / 2;
            final int halfWidth = width / 2;
            while ((halfHeight / inSampleSize) >= reqHeight
                    && (halfWidth / inSampleSize) >= reqWidth) {
                inSampleSize *= 2;
            }
        }
        return inSampleSize;
    }
}